package org.example.other;

import org.openjdk.jol.info.ClassLayout;

/**
 * 参考：<a href="https://juejin.cn/post/7495377687067574310">Java 对象头（Object Header）结构</a>
 * 查看java 对象在内存中的布局
 * Java 对象头（Object Header）结构，共三部分：对象头（Header）、实例数据（Instance Data）和对齐填充（Padding）
 */
public class JavaObjectLayout {
    public static void main(String[] args) {
        String obj = "789";
        System.out.println(ClassLayout.parseInstance(obj).toPrintable());

        synchronized (obj) {
            System.out.println(ClassLayout.parseInstance(obj).toPrintable());
        }
    }
}
/*
打印输出：
java.lang.Object object internals:
OFF  SZ   TYPE DESCRIPTION               VALUE
  0   8        (object header: mark)     0x0000000000000001 (non-biasable; age: 0) // 无锁
  8   4        (object header: class)    0x00164398
 12   4        (object alignment gap)
Instance size: 16 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total

java.lang.Object object internals:
OFF  SZ   TYPE DESCRIPTION               VALUE
  0   8        (object header: mark)     0x0000000000000000 (thin lock: 0x0000000000000000) // 轻量锁
  8   4        (object header: class)    0x00164398
 12   4        (object alignment gap)
Instance size: 16 bytes
Space losses: 0 bytes internal + 4 bytes external = 4 bytes total
 */
